<?php
namespace app\user\common;
use think\Controller;
use think\Request;
use think\Session;
class Base extends Controller
{
    protected function _initialize() {
//		parent::_initialize();
	}

	// 判断用户是否登录
	protected function isLogin() {
		if (is_null(Session::get('user_id'))) {
			$this -> error('未登录，无权访问', url('user/index/login'));
		}
	}
	
	protected function isReadyin() {
		if (Session::get('user_id')) {
			$this -> error('已登录，无须重复登录', url('user/index/index'));
		}
	}
	protected function https_request($url, $data = null) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	protected function get_component_access_token() {
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
		$data = array("component_appid" => config('$appId'), "component_appsecret" => config('$appsecret'), "component_verify_ticket" => file_get_contents('./uploads/ticket.log'));
		$send_result = json_decode(file_get_contents('./uploads/component_access_token.log'));
		if ($send_result && ($send_result -> expires_in < time())) {
			$send = $this -> https_request($url, json_encode($data));
			//重新请求
			$send = json_decode($send, true);
//			var_dump($send);
//			die();
			//得到一个多维数组对象
			$send_result -> component_access_token = $send['component_access_token'];
			$send_result -> expires_in = (time() + 7000);
			file_put_contents('./uploads/component_access_token.log', json_encode($send_result));
		}
		return $send_result -> component_access_token;
	}
	protected function get_pre_auth_code() {
		$send_result = json_decode(file_get_contents('./uploads/pre_auth_code.log'));
		if ($send_result && ($send_result -> expires_in < time())) {
			$token = $this ->get_component_access_token();
			$url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
			$data = array("component_appid" => config('$appId'));
			$send = $this->https_request($url, json_encode($data));
			$send = json_decode($send, true);//得到一个多维数组对象
			$send_result -> pre_auth_code = $send['pre_auth_code'];
			$send_result -> expires_in = (time() + 500);
			file_put_contents('./uploads/pre_auth_code.log', json_encode($send_result));
		}
		return $send_result->pre_auth_code;
	}
}
